#!/bin/bash
###
 # @Author: wcx
 # @Email: 1055127249@qq.com
 # @Date: 2024-12-19 17:48:05
 # @LastEditors: wcx 1055127249@qq.com
 # @LastEditTime: 2025-01-22 09:00:55
 # @FilePath: \my-project\get-img.sh
 # @Description: 描述
### 

# 检查是否提供了参数
if [ "$#" -ne 1 ]; then
    echo "Usage: $0 <full_image_name_with_version_suffix>"
    exit 1
fi

# 完整的镜像名称作为参数
FULL_IMAGE_NAME=$1

# 使用正则表达式解析参数
# 假设镜像名前缀不包含冒号，版本号和后缀之间包含一个或多个连字符
if [[ $FULL_IMAGE_NAME =~ ^([^:]+):(.+)-([0-9]+)-(.+)$ ]]; then
    IMAGE_PREFIX=${BASH_REMATCH[1]}
    VERSION=${BASH_REMATCH[2]}
    NUMBER=${BASH_REMATCH[3]}
    SUFFIX=${BASH_REMATCH[4]}
else
    echo "Invalid image name format. Please use the format: <image_prefix>:<version>-<number>-<suffix>"
    exit 1
fi

# Docker 仓库地址
REPOSITORY=dev-bj.hatech.com.cn/guotaijunan-chaos

# 构建完整的镜像名称和标签
TAGGED_IMAGE="${REPOSITORY}/${IMAGE_PREFIX}:${VERSION}-${NUMBER}-${SUFFIX}"

# 拉取镜像
echo "Pulling image: $TAGGED_IMAGE"
docker pull "$TAGGED_IMAGE"

# 保存镜像为 tar 文件
TAR_FILE="${IMAGE_PREFIX}:${VERSION}-${NUMBER}-${SUFFIX}.tar"
echo "Saving image to tar file: $TAR_FILE"
docker save "$TAGGED_IMAGE" -o "$TAR_FILE"

# 使用 gzip 压缩 tar 文件
echo "Compressing tar file with gzip"
gzip "$TAR_FILE"

echo "Done. Compressed image saved as ${TAR_FILE}.gz"